import { useState, useEffect } from "react";
import { useLocation, useParams, useNavigate } from "react-router-dom";
import { Select, Button, Table, Modal, Form, Input } from "antd";
import { SearchOutlined, RedoOutlined, PlusOutlined } from "@ant-design/icons";
import DictStyle from "./dict.module.scss";
import { navDataColumn } from "./column";
import { queryNavType, queryNavList, modifyNavById,addNav } from "@/api/index.js";
import Blupload from "@/components/Blupload";

export default function NavData() {
  const params = useParams();
  console.log(params, "params");
  const nav = useNavigate();
  const location = useLocation();
  const [paginationObj, setPaginationObj] = useState({ page: 1, size: 10 });
  const [loading, setLoading] = useState(false);
  const [list, setList] = useState([]);
  const [dictInfoList, setInfoList] = useState([]);
  const [dictId, setDictId] = useState();
  const [editVisible, setEditVisible] = useState(false);
  const [addVisible, setAddVisible] = useState(false);

  const [titleImg, setTitleImg] = useState("");
  const [addTitleImg, setAddTitleImg] = useState("");
  const [modifyId, setModifyId] = useState(-1);
  const requireRule = { required: true, message: "必填字段" };
  const [form] = Form.useForm();
  const [addform] = Form.useForm();
  useEffect(() => {
    getList();
    getDictInfoList();
  }, []);
  console.log("data", location);

  //获取select枚举
  const getDictInfoList = async () => {
    const res = await queryNavType();
    console.log("dictenum", res);
    setInfoList(res.data);
  };

  // 请求dict数据
  const getList = async (requestId = null) => {
    let id = useQuery().get("typeId");
    let requestObj = {};
    if (requestId) {
      requestObj.typeId = requestId;
    } else {
      requestObj.typeId = id;
    }
    const res = await queryNavList(requestObj);
    console.log("res", res);
    setList(res.data);
  };

  function useQuery() {
    return new URLSearchParams(location.search);
  }

  const handlePageChange = (page, size) => {
    // getList({ page, size });
  };

  const handleSizeChange = (page, size) => {
    // getList({ page, size });
  };

  // select的value变化
  const handleChangeSearch = (value) => {
    setDictId(value);
  };

  // 返回
  const handleBack = () => {
    nav(location.state.originPath);
  };
  //重置
  const handleResetSearch = () => {
    setDictId(null);
  };
  // 查询
  const handleSearch = () => {
    console.log(dictId, "dictId");
    getList(dictId);
  };

  // 编辑
  const handleOpenEditVisible = (row) => {
    setModifyId(row.id);
    console.log(row, "数据");
    const { logo, title, description, ip_address } = row;
    form.setFieldsValue({
      title,
      description,
      ip_address,
    });
    setTitleImg(logo);
    setEditVisible(true);
  };

  const handleCloseEditVisible = () => {
    setEditVisible(false);
    form.resetFields();
    setModifyId(-1);
  };
  const handleFinish = async (value) => {
    const requestObj = value;
    requestObj.logo = titleImg;
    requestObj.id = modifyId;
    console.log(requestObj, "value");
    const res = await modifyNavById(requestObj);
    if (res && res.code == 200) {
      window.$message.success("修改成功！");
    }
    handleCloseEditVisible();
    getList();
  };

  // 自定义处理上传

  const handleUploadChange = (titleImg) => {
    if (titleImg != "delete") {
      console.log(titleImg, "title");
      setTitleImg(titleImg);
    } else {
      setTitleImg("");
    }
  };

  const handleAddUploadChange = (titleImg) => {
    if (titleImg != "delete") {
      console.log(titleImg, "title");
      setAddTitleImg(titleImg);
    } else {
      setAddTitleImg("");
    }
  };
  const handleFinishFail = () => {};
  // 点击switch
  const handleSwitchStatus = async (row) => {
    const { id, status } = row;
    let requestObj = { id };
    if (status === 1) {
      requestObj.status = 0;
    } else {
      requestObj.status = 1;
    }
    console.log(requestObj, "switch");
    const res = await modifyNavById(requestObj);
    if (res && res.code == 200) {
      window.$message.success("修改成功！");
    }
    getList();
  };

  // 新增
  const handleCloseAddVisible = () => {
    setAddVisible(false);
    addform.resetFields();
    setAddTitleImg("");
  };
  const handleOpenAddVisible = () => {
    setAddVisible(true);
  };

  const handleAddFinishFail = () => {};

  const handleAddFinish = async (value) => {
    let id = useQuery().get("typeId");
    const requestObj = value;
    requestObj.typeId = id;
    requestObj.logo = addTitleImg;
    console.log(requestObj, "value");
    const res = await addNav(requestObj);
    if (res && res.code == 200) {
      window.$message.success("添加成功！");
    }
    handleCloseAddVisible();
    getList();
  };

  const columns = navDataColumn({ handleOpenEditVisible, handleSwitchStatus });
  return (
    <div className={DictStyle.dict}>
      <div className={DictStyle.top}>
        <div className={DictStyle.search}>
          <h3>导航分类:</h3>
          <Select
            value={dictId}
            style={{ width: "200px", marginRight: "10px" }}
            options={dictInfoList}
            fieldNames={{ label: "name", value: "id" }}
            onChange={handleChangeSearch}
          ></Select>
          <Button
            icon={<SearchOutlined />}
            type="primary"
            className={DictStyle["ant-btn"]}
            onClick={handleSearch}
          >
            查找
          </Button>
          <Button
            icon={<RedoOutlined />}
            className={DictStyle["ant-btn"]}
            onClick={handleResetSearch}
          >
            重置
          </Button>
        </div>
        <Button
          style={{ background: "#e6a23c", color: "#fff", border: "none",marginRight:'20px' }}
          onClick={handleBack}
        >
          返回
        </Button>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={handleOpenAddVisible}
        >
          新增
        </Button>
      </div>
      <div className={DictStyle["table-container"]}>
        <Table
          bordered
          columns={columns}
          dataSource={list}
          rowKey={(record) => record.id}
          loading={loading}
          pagination={{
            pageSize: paginationObj.pageSize,
            current: paginationObj.currentPage,
            pageSizeOptions: [3, 5, 10, 20],
            showSizeChanger: true,
            total: paginationObj.total,
            showTotal: (total) => `共${total}条`,
            onChange: handlePageChange,
            onShowSizeChange: handleSizeChange,
          }}
        />
      </div>
      {/* 编辑 */}
      <Modal
        open={editVisible}
        onCancel={handleCloseEditVisible}
        title="编辑友情链接"
        footer={false}
      >
        <Form
          style={{ padding: "20px" }}
          form={form}
          onFinishFailed={handleFinishFail}
          onFinish={handleFinish}
        >
          <Form.Item label="头像">
            <Blupload
              handleUploadChange={handleUploadChange}
              titleImg={titleImg}
            />
          </Form.Item>
          <Form.Item label="网站标题" name="title" rules={[requireRule]}>
            <Input></Input>
          </Form.Item>
          <Form.Item label="网站描述" name="description" rules={[requireRule]}>
            <Input></Input>
          </Form.Item>
          <Form.Item label="网站导航" name="ip_address" rules={[requireRule]}>
            <Input></Input>
          </Form.Item>

          <Form.Item style={{ textAlign: "center" }}>
            <Button
              onClick={handleCloseEditVisible}
              style={{ marginRight: "40px" }}
            >
              取消
            </Button>
            <Button type="primary" htmlType="submit">
              确定
            </Button>
          </Form.Item>
        </Form>
      </Modal>
      {/* 新增 */}
      <Modal open={addVisible} onCancel={handleCloseAddVisible} footer={null} title="新增导航">
        <Form
          style={{ padding: "20px" }}
          form={addform}
          onFinishFailed={handleAddFinishFail}
          onFinish={handleAddFinish}
        >
          <Form.Item label="头像">
            <Blupload
              handleUploadChange={handleAddUploadChange}
              titleImg={addTitleImg}
            />
          </Form.Item>
          <Form.Item label="网站名称" name="title" rules={[requireRule]}>
            <Input></Input>
          </Form.Item>
          <Form.Item label="网站描述" name="description" rules={[requireRule]}>
            <Input></Input>
          </Form.Item>
          <Form.Item label="网站地址" name="ip_address" rules={[requireRule]}>
            <Input></Input>
          </Form.Item>

          <Form.Item style={{ textAlign: "center" }}>
            <Button
              onClick={handleCloseAddVisible}
              style={{ marginRight: "40px" }}
            >
              取消
            </Button>
            <Button type="primary" htmlType="submit">
              确定
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}
